package com.qsl.file;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Optional;

/**
 * @Description:
 * @Author: 博客园@青石路
 * @CreateDate: 2023/5/15 14:02
 **/
public class EncodingTest {

    public static void main(String[] args) throws IOException {
        String filePath = "D:/hello.txt";
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        FileChannel channel = raf.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(10240);
        buffer.clear();
        byte[] sd = "hello|游戏|23".getBytes("GBK");
        writeLine(sd, channel, buffer);
        channel.close();
        raf.close();
    }

    private static int writeLine(byte[] bytes, FileChannel fc, ByteBuffer buffer) throws IOException {
        ByteBuffer byteBuffer = Optional.ofNullable(buffer).orElse(ByteBuffer.allocate(10240));
        int capacity = byteBuffer.capacity();
        int from = 0;

        int len = capacity;
        while(from < bytes.length) {
            if((len+from) > bytes.length) {
                len = bytes.length - from;
            }
            byteBuffer.clear();
            byteBuffer.put(ByteBuffer.wrap(bytes, from, len));
            byteBuffer.flip();
            fc.write(byteBuffer);
            from += len;
        }
        return from;
    }
}
